package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import com.alibaba.fastjson.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import com.alibaba.fastjson.parser.Feature
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import cn.com.elite.Util
import cn.com.kh.signUtil


/**
 * 工单查询API
 */

public class apiWoMessageEntrance implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiWoMessageEntrance.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        long startTime = System.currentTimeMillis();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");

        // 初始化返回参数
        JSONObject result = new JSONObject();

        JSONObject resultJson = null;
        //接收客户端调用参数
        String callJson = "";
        InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
        BufferedReader iny = new BufferedReader(reader);
        String line;
        while ((line = iny.readLine()) != null) {
            callJson += line;
        }

        log.info("[调用请求信息]:" + callJson);

        try {

            log.info("获取签名");
            //获取签名
//            JSONObject callJsono = JSONObject.parseObject(callJson, Feature.OrderedField);
//            String appkey = "123213123ACCESS_KEY";
//            String access_secret = "123213123ACCESS_SECRET";
//            long timestamp = System.currentTimeMillis()
//            String timestamps = String.valueOf(timestamp);
//            log.info("timestamps:"+timestamps);
//            callJsono.put("access_key", appkey);
//            callJsono.put("nonce", KHUtil.getRandomString(8));
//            callJsono.put("timestamp", timestamps);
//            log.info("callJsono:"+callJsono);
//            String sign = signUtil.getSign(callJsono, appkey, access_secret);
//            log.info("**********************");
//            callJsono.put("sign", sign);
//            log.info("sign:"+sign);
//            log.info("callJsono:"+callJsono);

            //解析Json
            JSONObject inJson = JSONObject.parseObject(callJson);
            //获取页面信息参数
            String in_s_objetive_guid = inJson.getJSONObject("data").getString("in_s_objetive_guid"); //当前objective_guid
            String in_s_elitetask_guid = inJson.getJSONObject("data").getString("in_s_elitetask_guid"); //当前elitetask_guid
            String in_r_map_id = inJson.getJSONObject("data").getString("in_r_map_id"); //当前mapid
            String in_r_node_id = inJson.getJSONObject("data").getString("in_r_node_id"); //当前nodeid
            String send_url = inJson.getJSONObject("data").getString("in_r_remark"); //当前通知remark(页面内目前只传支付链接)
            String in_r_objectivesubstatus = inJson.getJSONObject("data").getString("in_r_objectivesubstatus"); //当前通知remark
            String in_map_roleid = inJson.getJSONObject("data").getString("in_map_roleid"); //当前工单可操作的角色

            Integer sendSuccNum = 0;
            Integer sendFailNum = 0;
            String autoSendStatus = "";
            String dealCode = "";
            String dealMessage = "";

            log.info("in_s_objetive_guid:" + in_s_objetive_guid);
            log.info("in_s_elitetask_guid:" + in_s_elitetask_guid);
            log.info("send_url:" + send_url);
            log.info("in_r_map_id:" + in_r_map_id);
            log.info("in_r_node_id:" + in_r_node_id);
            log.info("in_r_objectivesubstatus:" + in_r_objectivesubstatus);
            log.info("in_map_roleid:" + in_map_roleid);
            //查询短信待发送数据
            String queryMessageSQL = "select send_type,auto_to_worker,remark,send_cust_type,case when send_cust_type = 'staff' then send_to_staff when send_cust_type = 'rolegroup' then send_to_group else '' end as send_user_id\n" +
                    "  from send_message_config where del_flag = '0' and map_id = '" + in_r_map_id + "' and operation_type = '" + in_r_objectivesubstatus + "' and node_id = '" + in_r_node_id + "'";

            log.info("执行任务数据查询SQL:" + queryMessageSQL);
            List WorkMessageList = eliteBean.chaxun_sql(queryMessageSQL, "dataSource");
            //获取总行数
            log.info("执行工单查询数据SQL获取总条数:" + WorkMessageList.size());

            for (int i = 0; i < WorkMessageList.size(); i++) {

                Map selectResultcm = WorkMessageList.get(i);
                String send_target = selectResultcm.get("send_cust_type");
                String send_type = selectResultcm.get("send_type");
                String send_user_id = selectResultcm.get("send_user_id");
                String send_remark = selectResultcm.get("remark");
                String auto_to_worker = selectResultcm.get("auto_to_worker");

                log.info("send_target:" + send_target);
                log.info("send_type:" + send_type);
                log.info("send_user_id:" + send_user_id);
                log.info("send_remark:" + send_remark);
                log.info("auto_to_worker:" + auto_to_worker);

                //当前通知需要通知到工单当前处理组或人
                if(auto_to_worker == "AUTO")
                {
                    log.info("开始短信自动发送当前处理人逻辑：");
                    String AutoSendMessageSQL = "select handlegroup_id,handleby_id from elitetask where elitetask_guid = '" + in_s_elitetask_guid + "' limit 1";
                    //String AutoSendMessageSQL = "select handlegroup_id,handleby_id from elitetask where objetive_guid = '" + in_s_objetive_guid + "' limit 1";
                    log.info("执行任务数据查询SQL:" + AutoSendMessageSQL);
                    List AutoSendMessageList = eliteBean.chaxun_sql(AutoSendMessageSQL, "dataSource");
                    log.info("获取查询条数：" + AutoSendMessageList.size());
                    if (AutoSendMessageList.size()==0)
                    {
                        autoSendStatus = "AUTOFAIL";
                    }

                    for (int j = 0; j<AutoSendMessageList.size(); j++)
                    {
                        Map AutoSendResultcm = AutoSendMessageList.get(j);
                        String auto_handlegroup = AutoSendResultcm.get("handlegroup_id");
                        String auto_handlestaff = AutoSendResultcm.get("handleby_id");
                        log.info("auto_handlegroup:" + auto_handlegroup);
                        log.info("auto_handlestaff:" + auto_handlestaff);

                        if(auto_handlegroup != "" && auto_handlestaff != "")
                        {
                            send_target = "staff";
                            send_user_id = auto_handlestaff;
                            log.info('AUTO-STAFF:' + send_user_id);

                        }else if(auto_handlegroup != "" && auto_handlestaff == "")
                        {
                            send_target = "rolegroup";
                            send_user_id = auto_handlegroup;
                            log.info('AUTO-GROUP:' + send_user_id);
                        }else
                        {
                            autoSendStatus = "AUTOFAIL";
                        }
                    }
                }

                //水电工抄水表后通知物业部职员
                if(auto_to_worker == "WYB")
                {
                    log.info("开始短信自动发送至物业部职员：");
                    String AutoWYBMessageSQL = "select oldhandlegroup_id,oldhandleby_id from workorderstep3 " +
                    "where workorder_guid = '" + in_s_objetive_guid +"' " +
                    "and to_stepidmap = '" + in_r_node_id + "' " +
                    "and from_stepidmap != to_stepidmap " +
                    "and from_stepidmap !='' " +
                    "and from_stepidmap is not null " +
                    "order by modifieddate desc " +
                    "limit 1 ";
                    log.info("执行任务数据查询SQL:" + AutoWYBMessageSQL);
                    List AutoWYBMessageList = eliteBean.chaxun_sql(AutoWYBMessageSQL, "dataSource");
                    log.info("获取查询条数：" + AutoWYBMessageList.size());
                    if (AutoWYBMessageList.size()==0)
                    {
                        autoSendStatus = "AUTOFAIL";
                    }

                    for (int j = 0; j<AutoWYBMessageList.size(); j++)
                    {
                        Map AutoSendResultcm = AutoWYBMessageList.get(j);
                        String auto_handlegroup = AutoSendResultcm.get("oldhandlegroup_id");
                        String auto_handlestaff = AutoSendResultcm.get("oldhandleby_id");
                        log.info("auto_handlegroup:" + auto_handlegroup);
                        log.info("auto_handlestaff:" + auto_handlestaff);

                        if(auto_handlegroup != "" && auto_handlestaff != "")
                        {
                            send_target = "staff";
                            send_user_id = auto_handlestaff;
                            log.info('AUTO-STAFF:' + send_user_id);

                        }else if(auto_handlegroup != "" && auto_handlestaff == "")
                        {
                            send_target = "rolegroup";
                            send_user_id = auto_handlegroup;
                            log.info('AUTO-GROUP:' + send_user_id);
                        }else
                        {
                            autoSendStatus = "AUTOFAIL";
                        }
                    }

                }

                String post_body = '''{  "data":{''' +
                        ''' "send_type":"''' + send_type + '''",''' +
                        ''' "send_target":"''' + send_target + '''",''' +
                        ''' "workorder_guid":"''' + in_s_objetive_guid + '''",''' +
                        ''' "elitetask_guid":"''' + in_s_elitetask_guid + '''",''' +
                        ''' "send_url":"''' + send_url + '''",''' +
                        ''' "user_id":"''' + send_user_id + '''",''' +
                        ''' "role_id":"''' + in_map_roleid + '''",''' +
                        ''' "send_remark":"''' + send_remark + '''"} }''';
                log.info("post_body:" + post_body);

                if (autoSendStatus == "AUTOFAIL")
                {
                    sendFailNum = sendFailNum + 1;
                    dealCode = "-1";
                    dealMessage = "处理失败，未查询到通知坐席！调用问题处理时长(毫秒):"
                }else
                {
                    // 调用API处理工单消息
                    String woOperationURL = KHDBConfig.getAPIURL(eliteBean, "NGS-Local") + "/ngsapitask/api/apiWOSendNotice";
                    String woOperationResult = Util.doHttpPost(woOperationURL, post_body, "UTF-8", 5000, 0);
                    JSONObject woOperationJson = JSONObject.parseObject(woOperationResult);
                    String re_code = woOperationJson.getString("code");
                    if (re_code.equals("1")) {
                        sendSuccNum = sendSuccNum + 1;
                        dealCode = "1";
                        dealMessage = "处理完成、调用问题处理时长(毫秒):"
                    } else {
                        sendFailNum = sendFailNum + 1;
                        dealCode = "-1";
                        dealMessage = "处理失败，短信发送失败！调用问题处理时长(毫秒):"
                    }
                }
            }

            long endTime = System.currentTimeMillis();
            result.put("code", dealCode);
            result.put("msg", dealMessage + (endTime - startTime));

        } catch (Exception e) {
            result.put("code", 1008);
            result.put("msg", e.getMessage());
        }

        return result.toString();

    }
}